/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 * @description 前序遍历 迭代
 */

var preorderTraversal = function (root) {
    // 初始化结果数组
    let res = []
    if (!root)
        return res
    // 初始化栈结构
    let stack = []
    // 将根节点压栈
    stack.push(root)
    while (stack.length) {
        // 将根节点出栈 放入res 
        const cur = stack.pop()
        res.push(cur.val)
        // 放入右左子节点
        if (cur.right) {
            stack.push(cur.right)
        }
        if (cur.left) {
            stack.push(cur.left)
        }
    }
    return res
};
